<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/6/7
 * Time: 下午4:10
 */

namespace App\Logic;
use App\Http\Model\AccessToken AS AccessTokenModel;
use App\Exceptions\ApiException;
use DB;

class AccessToken
{
    private $_accessToken = null;

    public function __construct($token)
    {
        $this->_accessToken = $token;
    }

    /**根据token返回tokenlogic对象
     * @param $token 用户token
     * @throws ApiException
     */
    public static function initByToken($token)
    {
        $access_token = AccessTokenModel::where('access_token', $token)->first();
        if (empty($access_token))
        {
            throw new ApiException('错误的token信息', 1000);
        }
        return new static($access_token);
    }

    public static function create($data)
    {
        if (empty($data['uuid']))
        {
            throw new ApiException('设备信息异常',1001);
        }
        DB::beginTransaction();
        Device::findAndSave($data);
        $tokenModel = new AccessTokenModel();
        $tokenModel->setToken()->setDevice($data['uuid'])->save();
        DB::commit();
        return new static($tokenModel);
    }
    
    public function login()
    {
        $this->getToken()->setLogin();
        return $this;
    }

    public function logout()
    {
        $this->getToken()->logout();
        return $this;
    }

    public function save($data = array())
    {
        if (!$this->getToken()->fill($data)->save())
        {
            throw  new ApiException('-2',"token信息保存失败");
        }
    }

    public function getToken()
    {
        return $this->_accessToken;
    }

    public function getUser()
    {
        return $this->_accessToken->user;
    }

    public function toApi()
    {
        $apiData = [
            'token' => (string)$this->getToken()->access_token,
            'uid' => (int)$this->getToken()->user_id,
            'status' => (int)$this->getToken()->status,
        ];
        return $apiData;
    }

}